using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Runtime.Serialization.Formatters.Binary;
using System.Configuration;
using Common;
using Common.Enum;
using Define;
using device;
using PcrDataAnalysis;
using PcrDataStructure;
using PcrExperimentProject;
using PluginFrame;
using SProject;
using SProject.BasicInformation;
using SProject.Paramter;
using SProject.Program;
using SystemConfiguration;

namespace SExperiment
{
    /// <summary>
    /// 读取PCR文件类
    /// </summary>
    public class ReadOldPcr
    {
        public static Experiment Read(string fileName)
        {
            PcrDataFile pcrDataFile = null;
            FileStream fileStream = null;
            try
            {
                fileStream = new FileStream(fileName, FileMode.Open);
                BinaryFormatter binaryFormatter = new BinaryFormatter();
                object obj = binaryFormatter.Deserialize(fileStream);
                if (obj != null)
                {
                    pcrDataFile = obj as PcrDataFile;
                }
            }
            catch (Exception)
            {
            }
            finally
            {
                if (fileStream != null)
                {
                    fileStream.Close();
                }
            }
            Experiment experiment = null;
            if (pcrDataFile != null)
            {
                IPcrExperiment pcrExperiment = pcrDataFile.CurrentPcrStructure.PcrExperiments[0];
                EProjectType type = EProjectType.AQ;
                List<Project> list = new List<Project>();
                foreach (IPcrExperimentProject project3 in pcrExperiment.Projects)
                {
                    Project project = new Project();
                    project.Password = project3.Password;
                    project.BasicInfo.Name = project3.Name;
                    project.BasicInfo.Reaction = pcrExperiment.TubeVolume;
                    project.BasicInfo.Unit = project3.Unit;
                    project.BasicInfo.Note = project3.Remark;
                    switch (pcrDataFile.CurrentPcrStructure.SystemType)
                    {
                        case PcrSystemType.AbsoluteAnalysis:
                            type = (project3.PcrProgram.HasAvailableMeltingSegment() ? EProjectType.Melt : EProjectType.AQ);
                            break;
                        case PcrSystemType.GeneScan:
                            type = EProjectType.HRM;
                            break;
                        case PcrSystemType.Allele:
                            type = EProjectType.AD;
                            break;
                    }
                    project.BasicInfo.Type = type;
                    project.PCRProgram = ConvertProgram(project3.PcrProgram);
                    Target target = new Target();
                    IProjectItem[] projectItems = project3.ProjectItems;
                    foreach (IProjectItem projectItem in projectItems)
                    {
                        if (projectItem == null)
                        {
                            continue;
                        }
                        for (int j = 0; j < projectItem.TubeAnalysisParameterConfiguration.Count; j++)
                        {
                            IAnalysisParameterConfiguration analysisParameterConfiguration = projectItem.TubeAnalysisParameterConfiguration[j];
                            if (!string.IsNullOrEmpty(analysisParameterConfiguration.ProjectName) && !(analysisParameterConfiguration.ProjectName == "N/A"))
                            {
                                TargetItem targetItem = new TargetItem();
                                targetItem.TubeNo = j + 1;
                                targetItem.TubeName = Utility.GetMessage("Prj_TubeDispaly") + targetItem.TubeNo;
                                targetItem.ChannelNo = analysisParameterConfiguration.ProjectChannel + 1;
                                targetItem.Name = analysisParameterConfiguration.ProjectName;
                                switch (targetItem.ChannelNo)
                                {
                                    case 1:
                                        targetItem.Dye = Utility.GetMessage("Channel1_Wave_Fam");
                                        break;
                                    case 2:
                                        targetItem.Dye = Utility.GetMessage("Channel2_Wave_VIC");
                                        break;
                                    case 3:
                                        targetItem.Dye = Utility.GetMessage("Channel3_Wave_Rox");
                                        break;
                                    case 4:
                                        targetItem.Dye = Utility.GetMessage("Channel4_Wave_Cy5");
                                        break;
                                }
                                target.Items.Add(targetItem);
                            }
                        }
                    }
                    project.UpdataTarget(target);
                    projectItems = project3.ProjectItems;
                    foreach (IProjectItem projectItem2 in projectItems)
                    {
                        if (projectItem2 == null)
                        {
                            continue;
                        }
                        for (int k = 0; k < projectItem2.TubeAnalysisParameterConfiguration.Count; k++)
                        {
                            IAnalysisParameterConfiguration oldTubeItem = projectItem2.TubeAnalysisParameterConfiguration[k];
                            BasicOptionItem basicOptionItem = project.BasicOption.Items.Where((BasicOptionItem s) => s.TubeNo == k + 1 && s.ChannelNo == oldTubeItem.ProjectChannel + 1).FirstOrDefault();
                            if (basicOptionItem != null && oldTubeItem is AbsoluteAnalysisParameterConfiguration)
                            {
                                AbsoluteAnalysisParameterConfiguration absoluteAnalysisParameterConfiguration = oldTubeItem as AbsoluteAnalysisParameterConfiguration;
                                switch (absoluteAnalysisParameterConfiguration.AbsoluteAnalysisType)
                                {
                                    case AbsoluteAnalysisType.Qualitative:
                                        basicOptionItem.AnalysisType = EAnalysisType.ANALYSIS_QUALITATIVE;
                                        break;
                                    case AbsoluteAnalysisType.Quantitative:
                                        basicOptionItem.AnalysisType = EAnalysisType.ANALYSIS_QUANTITATIVE;
                                        break;
                                }
                                basicOptionItem.BeginBaseline = absoluteAnalysisParameterConfiguration.StartBaseline;
                                basicOptionItem.EndBaseline = absoluteAnalysisParameterConfiguration.StopBaseline;
                                switch (absoluteAnalysisParameterConfiguration.BaselineOptimization)
                                {
                                    case BaselineOptimization.AutoOptimization:
                                        basicOptionItem.OptimizationMode = EOptionzationMode.OPTIMIZATION_AUTO;
                                        break;
                                    case BaselineOptimization.ManualOptimization:
                                        basicOptionItem.OptimizationMode = EOptionzationMode.OPTIMIZATION_MANUAL;
                                        break;
                                    case BaselineOptimization.NonOptimization:
                                        basicOptionItem.OptimizationMode = EOptionzationMode.OPTIMIZATION_NA;
                                        break;
                                }
                                basicOptionItem.AutoThreshold = absoluteAnalysisParameterConfiguration.IsAutoThreshold;
                                basicOptionItem.Threshold = absoluteAnalysisParameterConfiguration.ManualThreshold;
                                basicOptionItem.DigitalFilter = ((!absoluteAnalysisParameterConfiguration.IsDigitalFilter) ? EDigitalFilter.Normal : EDigitalFilter.None);
                            }
                        }
                        for (int l = 0; l < projectItem2.TubeMeltingAnalysisParameterConfiguration.Count; l++)
                        {
                            IAnalysisParameterConfiguration oldTubeItem2 = projectItem2.TubeMeltingAnalysisParameterConfiguration[l];
                            BasicOptionItem basicOptionItem2 = project.BasicOption.Items.Where((BasicOptionItem s) => s.TubeNo == l + 1 && s.ChannelNo == oldTubeItem2.ProjectChannel + 1).FirstOrDefault();
                            if (basicOptionItem2 != null && oldTubeItem2 is MeltingAnalysisParameterConfiguration)
                            {
                                MeltingAnalysisParameterConfiguration meltingAnalysisParameterConfiguration = oldTubeItem2 as MeltingAnalysisParameterConfiguration;
                                MeltingOptionItem meltingOptionItem = basicOptionItem2 as MeltingOptionItem;
                                if (meltingOptionItem != null)
                                {
                                    meltingOptionItem.MinTemperature = meltingAnalysisParameterConfiguration.MinTemperature;
                                    meltingOptionItem.MaxTemperature = meltingAnalysisParameterConfiguration.MaxTemperature;
                                    meltingOptionItem.PeekHightThreshold = meltingAnalysisParameterConfiguration.NoiseThreshold;
                                }
                            }
                            if (basicOptionItem2 == null || !(oldTubeItem2 is HRMAnalysisParameterConfiguration))
                            {
                                continue;
                            }
                            HRMAnalysisParameterConfiguration hRMAnalysisParameterConfiguration = oldTubeItem2 as HRMAnalysisParameterConfiguration;
                            HRMOptionItem hRMOptionItem = basicOptionItem2 as HRMOptionItem;
                            if (hRMOptionItem != null)
                            {
                                hRMOptionItem.StartTemperatureBefore = hRMAnalysisParameterConfiguration.StartTemperatureBeforeMelting;
                                hRMOptionItem.EndTemperatureBefore = hRMAnalysisParameterConfiguration.StopTemperatureBeforeMelting;
                                hRMOptionItem.StartTemperatureAfter = hRMAnalysisParameterConfiguration.StartTemperatureAfterMelting;
                                hRMOptionItem.EndTemperatureAfter = hRMAnalysisParameterConfiguration.StopTemperatureAfterMelting;
                                hRMOptionItem.QualityThreshold = hRMAnalysisParameterConfiguration.QualityFactor;
                                hRMOptionItem.TemperatureShiftThreshold = hRMAnalysisParameterConfiguration.ShiftThreshold;
                                switch (hRMAnalysisParameterConfiguration.HRMAnalysisType)
                                {
                                    case HRMAnalysisType.AutoGroup:
                                        hRMOptionItem.TypeMethod = EHRMTypeMethod.Auto;
                                        break;
                                    case HRMAnalysisType.StandardGroup:
                                        hRMOptionItem.TypeMethod = EHRMTypeMethod.Standart;
                                        break;
                                }
                            }
                        }
                        AlleleAnalysisParameterConfiguration alleleAnalysisParameterConfiguration = projectItem2.AnalysisParameterConfiguration as AlleleAnalysisParameterConfiguration;
                        if (alleleAnalysisParameterConfiguration == null)
                        {
                            continue;
                        }
                        ADOption aDOption = project.BasicOption as ADOption;
                        if (aDOption != null)
                        {
                            switch (alleleAnalysisParameterConfiguration.AlleleAnalysisType)
                            {
                                case AlleleAnalysisType.AutoGroup:
                                    aDOption.TypeMethod = EADTypeMethod.Auto;
                                    break;
                                case AlleleAnalysisType.StandardGroup:
                                    aDOption.TypeMethod = EADTypeMethod.Standart;
                                    break;
                            }
                            aDOption.QualityThreshold = alleleAnalysisParameterConfiguration.QualityFactor;
                            aDOption.GainRatio = alleleAnalysisParameterConfiguration.GainRatio;
                        }
                        break;
                    }
                    foreach (CrossTalkItem item in project.CrossTalk.Items)
                    {
                        for (int m = 0; m < item.Value.Count; m++)
                        {
                            item.Value[m] = project3.CrossTalkValue[item.ChannelNo - 1, m];
                        }
                    }
                    list.Add(project);
                }
                experiment = new Experiment();
                experiment.Name = Path.GetFileNameWithoutExtension(fileName);
                experiment.DefaultPath = Path.GetDirectoryName(fileName);
                experiment.Type = type;
                experiment.Operator = pcrExperiment.Operator.Name;
                experiment.Auditor = pcrExperiment.Assessor.Name;
                experiment.Note = pcrExperiment.Remark;
                bool useModelA = false;
                bool useModelB = false;
                foreach (IPcrModule pcrModule in pcrExperiment.PcrModules)
                {
                    if (pcrModule.ModuleID == "A")
                    {
                        useModelA = !pcrModule.CanbeUsed;
                    }
                    else if (pcrModule.ModuleID == "B")
                    {
                        useModelB = !pcrModule.CanbeUsed;
                    }
                }
                experiment.UseModelA = useModelA;
                experiment.UseModelB = useModelB;
                experiment.UseHotBonnet = pcrExperiment.IsUseHotLid;
                switch (pcrExperiment.TemperatureControlType)
                {
                    case TemperatureControlType.Block:
                        experiment.TemperatureControlMode = ETemperatureControlMode.Module;
                        break;
                    case TemperatureControlType.Tube:
                        experiment.TemperatureControlMode = ETemperatureControlMode.Tube;
                        break;
                }
                switch (pcrExperiment.LightScanStyle)
                {
                    case LightScanStyle.AllChannel:
                        experiment.ScanMode = EScanMode.All;
                        break;
                    case LightScanStyle.ProjectChannel:
                        experiment.ScanMode = EScanMode.Project;
                        break;
                }
                experiment.Program = ConvertProgram(pcrExperiment.PcrProgram);
                experiment.Device.CurrentProfile = experiment.Program;
                experiment.Device.StartTime = pcrExperiment.StartTime;
                experiment.Device.StopTime = pcrExperiment.StopTime;
                experiment.Device.PortName = "COM4";
                experiment.Device.Series = pcrExperiment.PcrStructure.PcrInstrument.ID;
                int num = 0;
                foreach (IPcrModule pcrModule2 in pcrExperiment.PcrModules)
                {
                    num = ((!(pcrModule2.ModuleID == "A")) ? (num + 2) : (num + 1));
                }
                experiment.Device.UsedBlock = (byte)num;
                switch (pcrExperiment.PcrStructure.PcrInstrument.Type)
                {
                    case InstrumentType.SLAN48P:
                        experiment.Device.Model = Device.DeviceModel_48P;
                        experiment.Device.UsedHotlid = 1;
                        break;
                    case InstrumentType.SLAN96P:
                        experiment.Device.Model = Device.DeviceModel_96P;
                        experiment.Device.UsedHotlid = experiment.Device.UsedBlock;
                        break;
                    case InstrumentType.SLAN96S:
                        experiment.Device.Model = Device.DeviceModel_96S;
                        experiment.Device.UsedHotlid = 1;
                        break;
                }
                experiment.Device.HotlidIsHeating = pcrExperiment.IsUseHotLid;
                experiment.Device.HotlidSetTemperature = (int)pcrExperiment.HotLidSettingTemperature;
                experiment.Device.TemperatureControl = (byte)pcrExperiment.TemperatureControlType;
                experiment.Device.Volume = pcrExperiment.TubeVolume;
                experiment.Device.ScanMethod = (byte)pcrExperiment.LightScanStyle;
                for (int n = 0; n < 6; n++)
                {
                    string text = pcrExperiment.PcrStructure.PcrInstrument.ChannelNames[n];
                    if (!string.IsNullOrEmpty(text) && pcrExperiment.PcrStructure.PcrInstrument.ChannelConfigurations[text].IsAvailable)
                    {
                        experiment.Device.ChannelNo[n] = (byte)(n + 1);
                    }
                }
                List<double> list2 = new List<double>();
                for (int num2 = 0; num2 < 6; num2++)
                {
                    list2 = pcrExperiment.PcrStructure.PcrInstrument.ChannelCellGain[num2];
                    byte[] array = new byte[98];
                    for (int num3 = 0; num3 < 96; num3++)
                    {
                        array[num3] = (byte)(list2[num3] * 100.0);
                    }
                    double num4 = pcrExperiment.PcrStructure.PcrInstrument.GetChannelGain(num2) * 1000.0;
                    array[96] = (byte)(num4 / 256.0);
                    array[97] = (byte)(num4 % 256.0);
                    experiment.Device.Calibration.Add(array);
                }
                experiment.Device.RunError = RunningError.None;
                experiment.Device.RunState = RunningState.Finish;
                int acquisitionCycleCount = experiment.Program.GetAcquisitionCycleCount();
                List<IPcrCell> pcrCellsInExperiment = pcrExperiment.GetPcrCellsInExperiment();
                int count = pcrCellsInExperiment[0].LightRawByteData.Count;
                for (int num5 = 0; num5 < acquisitionCycleCount; num5++)
                {
                    FluorescenceData[,] array2 = new FluorescenceData[96, 6];
                    for (int num6 = 0; num6 < 96; num6++)
                    {
                        for (int num7 = 0; num7 < 6; num7++)
                        {
                            if (array2[num6, num7] == null)
                            {
                                array2[num6, num7] = new FluorescenceData();
                            }
                            if (num6 < pcrCellsInExperiment.Count)
                            {
                                int num8 = pcrCellsInExperiment[num6].CellID - 1;
                                byte[,] array3 = pcrCellsInExperiment[num6].LightRawByteData[num5];
                                if (array2[num8, num7] == null)
                                {
                                    array2[num8, num7] = new FluorescenceData();
                                }
                                array2[num8, num7].Char1 = array3[num7, 0];
                                array2[num8, num7].Char2 = array3[num7, 1];
                                array2[num8, num7].Char3 = array3[num7, 2];
                                array2[num8, num7].Char4 = array3[num7, 3];
                            }
                        }
                    }
                    experiment.Device.RawData.Add(array2);
                }
                if (count > acquisitionCycleCount)
                {
                    for (int num9 = acquisitionCycleCount; num9 < count; num9++)
                    {
                        FluorescenceData[,] array4 = new FluorescenceData[96, 6];
                        for (int num10 = 0; num10 < 96; num10++)
                        {
                            for (int num11 = 0; num11 < 6; num11++)
                            {
                                if (array4[num10, num11] == null)
                                {
                                    array4[num10, num11] = new FluorescenceData();
                                }
                                if (num10 < pcrCellsInExperiment.Count)
                                {
                                    int num8 = pcrCellsInExperiment[num10].CellID - 1;
                                    byte[,] array5 = pcrCellsInExperiment[num10].LightRawByteData[num9];
                                    if (array4[num8, num11] == null)
                                    {
                                        array4[num8, num11] = new FluorescenceData();
                                    }
                                    array4[num8, num11].Char1 = array5[num11, 0];
                                    array4[num8, num11].Char2 = array5[num11, 1];
                                    array4[num8, num11].Char3 = array5[num11, 2];
                                    array4[num8, num11].Char4 = array5[num11, 3];
                                }
                            }
                        }
                        experiment.Device.RawMeltingData.Add(array4);
                    }
                }
                int count2 = experiment.Device.RawMeltingData.Count;
                if (count2 != 0)
                {
                    SProject.Program.MeltingSegment meltingSegment = experiment.Program.Programs.Where((BaseSegment s) => s is SProject.Program.MeltingSegment).Cast<SProject.Program.MeltingSegment>().FirstOrDefault();
                    double num12 = meltingSegment.StartTemp;
                    double num13 = (meltingSegment.EndTemp - meltingSegment.StartTemp) / (double)count2;
                    for (int num14 = 0; num14 < count2; num14++)
                    {
                        double[,] array6 = new double[96, 6];
                        for (int num15 = 0; num15 < 96; num15++)
                        {
                            for (int num16 = 0; num16 < 6; num16++)
                            {
                                array6[num15, num16] = num12;
                            }
                        }
                        experiment.Device.MeltingTemperatureData.Add(array6);
                        num12 += num13;
                    }
                }
                List<int> list3 = new List<int>();
                list3.Add(pcrExperiment.BlockTemperature.Count);
                if (pcrExperiment.TubeTemperature != null && pcrExperiment.TubeTemperature.Count != 0)
                {
                    list3.Add(pcrExperiment.TubeTemperature.Count);
                }
                if (pcrExperiment.HotLidTemperature != null && pcrExperiment.HotLidTemperature.Count != 0)
                {
                    list3.Add(pcrExperiment.HotLidTemperature.Count);
                }
                int num17 = list3.Min();
                for (int num18 = 0; num18 < num17; num18++)
                {
                    RunTemperature runTemperature = new RunTemperature();
                    runTemperature.BlockTemperature = pcrExperiment.BlockTemperature[num18];
                    if (pcrExperiment.TubeTemperature != null && pcrExperiment.TubeTemperature.Count != 0)
                    {
                        runTemperature.TubeTemperature = pcrExperiment.TubeTemperature[num18];
                    }
                    if (pcrExperiment.HotLidTemperature != null && pcrExperiment.HotLidTemperature.Count != 0)
                    {
                        runTemperature.HotlidTemperature = pcrExperiment.HotLidTemperature[num18];
                    }
                    runTemperature.TimeRecord = new TimeSpan((long)(num18 + 1) * 10000000L);
                    experiment.Device.RunTemperatureList.Add(runTemperature);
                }
                for (int num19 = 0; num19 < pcrExperiment.PcrModules.Count; num19++)
                {
                    for (int num20 = 0; num20 < pcrExperiment.PcrModules[num19].SubModules.Count; num20++)
                    {
                        for (int num21 = 0; num21 < pcrExperiment.PcrModules[num19].SubModules[num20].PcrCells.Count; num21++)
                        {
                            IPcrCell oldCell = pcrExperiment.PcrModules[num19].SubModules[num20].PcrCells[num21];
                            Well well = experiment.Wells[oldCell.CellID - 1];
                            if (oldCell.Project == null || well.Sample != null)
                            {
                                continue;
                            }
                            Sample sample = new Sample(list.Where((Project s) => s.BasicInfo.Name == oldCell.Project.Name).FirstOrDefault(), 0);
                            sample.CompoundTubeNo = oldCell.GetCellInformation("ReplicatedTubeKey", 0);
                            sample.PatientInfo.ID = oldCell.GetCellInformation("LabelKey", 0);
                            sample.PatientInfo.Name = oldCell.GetCellInformation("NameKey", 0);
                            sample.PatientInfo.Sex = oldCell.GetCellInformation("GenderKey", 0);
                            sample.PatientInfo.Age = oldCell.GetCellInformation("AgeKey", 0);
                            sample.PatientInfo.CaseID = oldCell.GetCellInformation("CaseIDKey", 0);
                            sample.PatientInfo.BedID = oldCell.GetCellInformation("BedIDKey", 0);
                            sample.PatientInfo.InPatientID = oldCell.GetCellInformation("In-patientIDKey", 0);
                            sample.PatientInfo.OutPatientID = oldCell.GetCellInformation("Out-patientIDKey", 0);
                            sample.PatientInfo.Specimen = oldCell.GetCellInformation("SampleTypeKey", 0);
                            sample.PatientInfo.SpecimenDate = oldCell.GetCellInformation("SampleDateKey", 0);
                            sample.PatientInfo.Doctor = oldCell.GetCellInformation("DoctorKey", 0);
                            sample.PatientInfo.Office = oldCell.GetCellInformation("OfficeKey", 0);
                            sample.PatientInfo.Diagnosis = oldCell.GetCellInformation("DiagnosisKey", 0);
                            sample.PatientInfo.Remark = oldCell.GetCellInformation("RemarkKey", 0);
                            for (int num22 = 0; num22 < oldCell.MultiTubeCells.Count; num22++)
                            {
                                IPcrCell pcrCell = oldCell.MultiTubeCells[num22];
                                well = experiment.Wells[pcrCell.CellID - 1];
                                well.IsInValid = pcrCell.IsBad;
                                foreach (SampleTargetItem item2 in sample.Items)
                                {
                                    if (item2.TubeNo == num22 + 1)
                                    {
                                        switch (pcrCell.GetCellInformation("DetectionTypeKey", item2.ChannelNo - 1))
                                        {
                                            case "标准品":
                                                item2.SampleType = SampleType.Standard;
                                                break;
                                            case "样品":
                                                item2.SampleType = SampleType.Unknown;
                                                break;
                                            case "阳性对照":
                                                item2.SampleType = SampleType.HighPositive;
                                                break;
                                            case "阴性对照":
                                                item2.SampleType = SampleType.Negative;
                                                break;
                                            case "NTC":
                                                item2.SampleType = SampleType.NTC;
                                                break;
                                            case "质控品":
                                                item2.SampleType = SampleType.QC;
                                                break;
                                        }
                                        item2.Property = pcrCell.GetCellInformation("PropertyKey", item2.ChannelNo - 1);
                                    }
                                }
                                well.SetSample(sample, num22 + 1);
                                well.Sample.Wells.Add(well);
                            }
                        }
                    }
                }
                experiment.Status = EExperimentStatus.Completed;
                if (pcrExperiment.CurrentImportStandardCurve != null)
                {
                    List<Project> allProject = experiment.CurrentSubset.GetAllProject();
                    foreach (KeyValuePair<string, IPcrStandardCurve> item3 in pcrExperiment.CurrentImportStandardCurve)
                    {
                        string prjName = item3.Key.ToString();
                        Project project2 = allProject.Where((Project s) => s.BasicInfo.Name == prjName).FirstOrDefault();
                        if (project2 == null)
                        {
                            continue;
                        }
                        IPcrStandardCurve value = item3.Value;
                        List<IPcrCell> list4 = new List<IPcrCell>();
                        Subset.SubsetParamter subsetParamter = experiment.CurrentSubset.GetSubsetParamter(project2);
                        if (subsetParamter != null)
                        {
                            ProjectStdCurve projectStdCurve2 = (subsetParamter.CurrentProjectStdCurve = new ProjectStdCurve());
                            ProjectStdCurve projectStdCurve3 = projectStdCurve2;
                            projectStdCurve3.ProjectName = prjName;
                            projectStdCurve3.Type = experiment.Type;
                            projectStdCurve3.External = true;
                            projectStdCurve3.Path = value.FileName;
                            projectStdCurve3.ExternalStdWell = new List<Well>();
                            foreach (IPcrCell standardPcrCell in value.GetStandardPcrCells(project2.BasicOption.Items.Min((BasicOptionItem s) => s.ChannelNo) - 1, 0))
                            {
                                if (list4.Contains(standardPcrCell))
                                {
                                    continue;
                                }
                                Sample sample2 = new Sample(project2, 0);
                                sample2.CompoundTubeNo = standardPcrCell.GetCellInformation("ReplicatedTubeKey", 0);
                                for (int num23 = 0; num23 < standardPcrCell.MultiTubeCells.Count; num23++)
                                {
                                    IPcrCell pcrCell2 = standardPcrCell.MultiTubeCells[num23];
                                    foreach (SampleTargetItem item4 in sample2.Items)
                                    {
                                        if (item4.TubeNo == num23 + 1)
                                        {
                                            switch (pcrCell2.GetCellInformation("DetectionTypeKey", item4.ChannelNo - 1))
                                            {
                                                case "标准品":
                                                    item4.SampleType = SampleType.Standard;
                                                    break;
                                                case "样品":
                                                    item4.SampleType = SampleType.Unknown;
                                                    break;
                                                case "阳性对照":
                                                    item4.SampleType = SampleType.HighPositive;
                                                    break;
                                                case "阴性对照":
                                                    item4.SampleType = SampleType.Negative;
                                                    break;
                                                case "NTC":
                                                    item4.SampleType = SampleType.NTC;
                                                    break;
                                                case "质控品":
                                                    item4.SampleType = SampleType.QC;
                                                    break;
                                            }
                                            item4.Property = pcrCell2.GetCellInformation("PropertyKey", item4.ChannelNo - 1);
                                        }
                                    }
                                    Well well2 = new Well();
                                    well2.ID = pcrCell2.CellID - 1;
                                    well2.SetSample(sample2, num23 + 1);
                                    well2.Sample.Wells.Add(well2);
                                    projectStdCurve3.ExternalStdWell.Add(well2);
                                    list4.Add(pcrCell2);
                                }
                            }
                            projectStdCurve3.ExternalTargetStdCurveList = new List<TargetStdCurve>();
                            IAnalysisResult[,] getStandardCurveData = value.GetStandardCurveData;
                            for (int num24 = 0; num24 < getStandardCurveData.GetLength(0); num24++)
                            {
                                for (int num25 = 0; num25 < getStandardCurveData.GetLength(1); num25++)
                                {
                                    if (getStandardCurveData[num24, num25] != null && value.CellCycles[num24, num25] != null)
                                    {
                                        QuantitativeAnalysisResult qaResult = getStandardCurveData[num24, num25] as QuantitativeAnalysisResult;
                                        TargetStdCurve targetStdCurve = new TargetStdCurve();
                                        targetStdCurve.TargetName = project2.BasicOption.Items.Where((BasicOptionItem s) => s.ChannelNo == qaResult.ProjectChannel + 1).FirstOrDefault().TargetName;
                                        targetStdCurve.Slope = qaResult.Slope;
                                        targetStdCurve.Intercept = qaResult.Intercept;
                                        targetStdCurve.r_Value = qaResult.SquareError;
                                        targetStdCurve.Efficiency = qaResult.AmplificationRate;
                                        targetStdCurve.StdDot = new List<Dot>();
                                        for (int num26 = 0; num26 < value.CellCycles[num24, num25].Count; num26++)
                                        {
                                            targetStdCurve.StdDot.Add(new Dot
                                            {
                                                X = value.CellConcentrations[num24, num25][num26],
                                                Y = value.CellCycles[num24, num25][num26]
                                            });
                                        }
                                        projectStdCurve3.ExternalTargetStdCurveList.Add(targetStdCurve);
                                    }
                                }
                            }
                        }
                        List<FluorescenceData[,]> list5 = new List<FluorescenceData[,]>();
                        for (int num27 = 0; num27 < allProject[0].PCRProgram.GetAcquisitionCycleCount(); num27++)
                        {
                            FluorescenceData[,] array7 = new FluorescenceData[96, 6];
                            for (int num28 = 0; num28 < 96; num28++)
                            {
                                for (int num29 = 0; num29 < 6; num29++)
                                {
                                    if (array7[num28, num29] == null)
                                    {
                                        array7[num28, num29] = new FluorescenceData();
                                    }
                                    if (num28 >= pcrCellsInExperiment.Count)
                                    {
                                        continue;
                                    }
                                    int id = pcrCellsInExperiment[num28].CellID - 1;
                                    IPcrCell pcrCell3 = list4.Where((IPcrCell s) => s.CellID - 1 == id).FirstOrDefault();
                                    if (pcrCell3 != null)
                                    {
                                        byte[,] array8 = pcrCell3.LightRawByteData[num27];
                                        if (array7[id, num29] == null)
                                        {
                                            array7[id, num29] = new FluorescenceData();
                                        }
                                        array7[id, num29].Char1 = array8[num29, 0];
                                        array7[id, num29].Char2 = array8[num29, 1];
                                        array7[id, num29].Char3 = array8[num29, 2];
                                        array7[id, num29].Char4 = array8[num29, 3];
                                    }
                                }
                            }
                            list5.Add(array7);
                        }
                        RawDataToRawCurve(list5, subsetParamter.CurrentProjectStdCurve.ExternalStdWell, experiment.Device.Calibration);
                    }
                }
                experiment.ExperimentSetting.ParamterVisible = !pcrExperiment.IsHideParameterPanel;
            }
            return experiment;
        }

        private static void RawDataToRawCurve(List<FluorescenceData[,]> rawData, List<Well> listWell, List<byte[]> calibration)
        {
            List<double>[,] array = new List<double>[96, 6];
            for (int i = 0; i < 96; i++)
            {
                for (int j = 0; j < 6; j++)
                {
                    array[i, j] = new List<double>();
                }
            }
            for (int k = 0; k < rawData.Count; k++)
            {
                FluorescenceData[,] array2 = rawData[k];
                for (int l = 0; l < 96; l++)
                {
                    for (int m = 0; m < 6; m++)
                    {
                        if (array2[l, m] == null)
                        {
                            continue;
                        }
                        double num = Conversion(array2[l, m]);
                        if (calibration.Count == 6)
                        {
                            byte[] array3 = calibration[m];
                            if (array3.Count() == 98 && num > -50.0 && array3[l] != byte.MaxValue && array3[l] != 0)
                            {
                                double num2 = (double)(int)array3[l] / 100.0;
                                double num3 = (double)(array3[96] * 256 + array3[97]) / 1000.0;
                                num = (num - 25.5) * num2 * num3;
                            }
                        }
                        if (num > -50.0 && num < 0.1)
                        {
                            num = 0.1;
                        }
                        array[l, m].Add(num);
                    }
                }
            }
            RawCurveCal(array, listWell);
            Curve curve = new Curve();
            Curve curve2 = new Curve();
            foreach (Well item in listWell)
            {
                if (item.Sample == null)
                {
                    continue;
                }
                CrossTalk crossTalk = item.Project.CrossTalk;
                foreach (SampleTargetItem item2 in item.Sample.Items)
                {
                    if (item2.TubeNo != item.MultiTubeID)
                    {
                        continue;
                    }
                    curve = item2.Result.RawCurve;
                    for (int n = 0; n < curve.CurvePoint.Count; n++)
                    {
                        foreach (CrossTalkItem item3 in crossTalk.Items)
                        {
                            foreach (SampleTargetItem item4 in item.Sample.Items)
                            {
                                if (item4.ChannelNo == item3.ChannelNo && item4.TubeNo == item.MultiTubeID)
                                {
                                    curve2 = item4.Result.RawCurve;
                                    curve.CurvePoint[n].Y = curve.CurvePoint[n].Y - curve2.CurvePoint[n].Y * item3.Value[item2.ChannelNo - 1] / 100.0;
                                    break;
                                }
                            }
                        }
                    }
                }
            }
        }

        private static void RawCurveCal(List<double>[,] RawData, List<Well> wells)
        {
            foreach (Well well in wells)
            {
                if (well.Sample == null)
                {
                    continue;
                }
                foreach (SampleTargetItem item in well.Sample.Items)
                {
                    if (item.TubeNo != well.MultiTubeID)
                    {
                        continue;
                    }
                    int iD = well.ID;
                    int channelNo = item.ChannelNo;
                    item.Result.RawCurve.CurvePoint.Clear();
                    int count = RawData[iD, channelNo - 1].Count;
                    for (int i = 0; i < count; i++)
                    {
                        Dot dot = new Dot();
                        dot.X = i + 1;
                        dot.Y = RawData[iD, channelNo - 1][i];
                        if ((i != 0 || !(dot.Y > 2000.0)) && !(dot.Y < -50.0))
                        {
                            item.Result.RawCurve.CurvePoint.Add(dot);
                        }
                    }
                    if (item.Result.RawCurve.CurvePoint.Count < count && item.Result.RawCurve.CurvePoint.Count >= 3)
                    {
                        item.Result.RawCurve = CurveInsert(item.Result.RawCurve, 1.0, count, 1.0);
                    }
                }
            }
        }

        private static Curve CurveInsert(Curve curve, double begin, double end, double interval)
        {
            int count = curve.CurvePoint.Count;
            Curve curve2 = new Curve();
            int num = 0;
            int i = 0;
            while (begin <= end + 0.0001)
            {
                for (; i != count - 1 && !(begin < curve.CurvePoint[i].X); i++)
                {
                }
                num = ((i > 2) ? (i - 2) : 0);
                Dot dot = new Dot();
                dot.X = begin;
                dot.Y = Insert(curve.CurvePoint[num].X, curve.CurvePoint[num + 1].X, curve.CurvePoint[num + 2].X, curve.CurvePoint[num].Y, curve.CurvePoint[num + 1].Y, curve.CurvePoint[num + 2].Y, dot.X);
                curve2.CurvePoint.Add(dot);
                begin += interval;
            }
            return curve2;
        }

        internal static double Insert(double x0, double x1, double x2, double y0, double y1, double y2, double x)
        {
            if (x == x0)
            {
                return y0;
            }
            if (x == x1)
            {
                return y1;
            }
            if (x == x2)
            {
                return y2;
            }
            return (x - x0) * (x - x1) * (x - x2) * (y0 / ((x0 - x1) * (x0 - x2) * (x - x0)) + y1 / ((x1 - x0) * (x1 - x2) * (x - x1)) + y2 / ((x2 - x0) * (x2 - x1) * (x - x2)));
        }

        internal static double Conversion(FluorescenceData FData)
        {
            double num = (int)FData.Char2;
            double num2 = (int)FData.Char3;
            double num3 = (int)FData.Char4;
            double num4;
            if (FData.Char1 == byte.MaxValue)
            {
                num4 = -100.0;
            }
            else
            {
                if ((FData.Char1 & 0x10) != 0)
                {
                    num3 = (int)(byte)(FData.Char4 | 0x80);
                }
                if ((FData.Char1 & 0x20) != 0)
                {
                    num2 = (int)(byte)(FData.Char3 | 0x80);
                }
                if ((FData.Char1 & 0x40) != 0)
                {
                    num = (int)(byte)(FData.Char2 | 0x80);
                }
                num4 = (num3 + num2 * 256.0 + num * 65536.0) / 1677.7214;
                if ((FData.Char1 & 1) != 0)
                {
                    num4 *= 8.0;
                }
            }
            return num4;
        }

        private static PCRProgram ConvertProgram(IPcrProgram oldProgram)
        {
            PCRProgram pCRProgram = new PCRProgram();
            for (int i = 0; i < Math.Min(oldProgram.AmplificationSegments.Count, oldProgram.AvailableAmplificationSegmentCount); i++)
            {
                AmplificationSegment amplificationSegment = oldProgram.AmplificationSegments[i] as AmplificationSegment;
                Segment segment = new Segment();
                segment.Name = amplificationSegment.Name;
                segment.Cycles = amplificationSegment.Cycle;
                foreach (DataRow row in amplificationSegment.StepTable.Rows)
                {
                    Step step = new Step();
                    step.Name = row["StepName"] as string;
                    step.Temperature = (double)row["Temperature"];
                    int num = CovertTimeStringToSecond(row["HoldTime"] as string);
                    step.HoldMinute = num / 60;
                    step.HoldSecond = num % 60;
                    step.IsAcquisition = (bool)row["Fluorescence"];
                    step.IsAdvProgram = (bool)row["Advanced"];
                    if (step.IsAdvProgram)
                    {
                        step.IsTempVarUp = (bool)row["TemperatureVariation"];
                        step.TempVarValue = (double)row["TemperatureValue"];
                        step.IsTimeVarUp = (bool)row["TimeVariation"];
                        step.TimeVarValue = CovertTimeStringToSecond(row["TimeValue"] as string);
                        step.IsUseRamp = true;
                        step.Ramp = (double)row["Rising/FallingRate"];
                    }
                    segment.Items.Add(step);
                }
                pCRProgram.Programs.Add(segment);
            }
            if (oldProgram.MeltingSegments.Count > 0 && !string.IsNullOrEmpty(oldProgram.MeltingSegments[0].HoldTime))
            {
                SProject.Program.MeltingSegment meltingSegment = new SProject.Program.MeltingSegment();
                meltingSegment.IsHRM = false;
                meltingSegment.Name = oldProgram.MeltingSegments[0].Name;
                meltingSegment.StartTemp = oldProgram.MeltingSegments[0].StartDegree;
                meltingSegment.EndTemp = oldProgram.MeltingSegments[0].StopDegree;
                meltingSegment.ScanMode = SProject.Program.MeltingSegment.SCAN_STEP;
                meltingSegment.Interval = oldProgram.MeltingSegments[0].StepInterval;
                meltingSegment.HoldTime = CovertTimeStringToSecond(oldProgram.MeltingSegments[0].HoldTime);
                pCRProgram.Programs.Add(meltingSegment);
            }
            if (oldProgram.HRMSegments.Count > 0 && !string.IsNullOrEmpty(oldProgram.HRMSegments[0].HoldTime))
            {
                SProject.Program.MeltingSegment meltingSegment2 = new SProject.Program.MeltingSegment();
                meltingSegment2.IsHRM = true;
                meltingSegment2.Name = oldProgram.HRMSegments[0].Name;
                meltingSegment2.StartTemp = oldProgram.HRMSegments[0].StartDegree;
                meltingSegment2.EndTemp = oldProgram.HRMSegments[0].StopDegree;
                meltingSegment2.Rate = oldProgram.HRMSegments[0].Rate;
                if (meltingSegment2.Rate == 0.0)
                {
                    meltingSegment2.ScanMode = SProject.Program.MeltingSegment.SCAN_CONTINUE;
                }
                else
                {
                    meltingSegment2.ScanMode = SProject.Program.MeltingSegment.SCAN_STEP;
                    meltingSegment2.Interval = oldProgram.HRMSegments[0].StepInterval;
                    meltingSegment2.HoldTime = CovertTimeStringToSecond(oldProgram.HRMSegments[0].HoldTime);
                }
                pCRProgram.Programs.Add(meltingSegment2);
            }
            return pCRProgram;
        }

        private static int CovertTimeStringToSecond(string time)
        {
            if (string.IsNullOrEmpty(time))
            {
                return 0;
            }
            int num = 0;
            int num2 = 0;
            string[] array = time.Split(':');
            for (int num3 = array.Length - 1; num3 >= 0; num3--)
            {
                num += Convert.ToInt32(array[num3]) * Convert.ToInt32(Math.Pow(60.0, num2));
                num2++;
            }
            return num;
        }
    }
}
